package com.example.demo.config;

import net.sf.ehcache.CacheManager;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.io.ResourceUtils;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: ElonChung
 * @Date:
 * @Description:
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroBean = new ShiroFilterFactoryBean();

        shiroBean.setSecurityManager(defaultWebSecurityManager);

        Map<String, Filter> filterMap = new LinkedHashMap<>();
        shiroBean.setFilters(filterMap);
        // 添加授权路径相关
        // ilterMap.put("/user/update","perms[user:update]");

        return shiroBean;
    }


    @Bean("securityManager")
    public DefaultWebSecurityManager defaultSecurityManager(@Qualifier("myRealm") MyRealm myRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(myRealm);
        return securityManager;
    }

    @Bean
    public MyRealm myRealm(@Qualifier("ehCache") EhCacheManager ehCacheManager) {
        MyRealm myRealm = new MyRealm();
        myRealm.setCacheManager(ehCacheManager);
        return myRealm;
    }


    /**
     * 注入Ehcache缓存.
     */
    @Bean(name = "ehCache")
    public EhCacheManager ehCacheManager(@Qualifier("ehcacheManager") CacheManager cacheManager) {

        EhCacheManager ehCacheManager = new EhCacheManager();

        ehCacheManager.setCacheManager(cacheManager);

        return ehCacheManager;
    }

    /**
     * 管理缓存 解决热部署 Ehcache重复创建CacheManager问题
     *
     * @return
     */
    @Bean(name = "ehcacheManager")
    public CacheManager ehCacheManagerFactoryBean() {
        System.out.println("执行了ehcache");
        CacheManager cacheManager = CacheManager.getCacheManager("es");
        if (cacheManager == null) {
            try {
                cacheManager = CacheManager.create(ResourceUtils.getInputStreamForPath("classpath:ehcache-shiro.xml"));
            } catch (IOException e) {
                throw new RuntimeException("initialize cacheManager failed");
            }
        }
        return cacheManager;
    }
}
